
import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon, Permission } from "pao-aop";
import { Form, Tree, Input, Row, Col, Button, message, Select, TreeSelect } from "antd";
import { MainCard } from "src/business/components/style-components/main-card";
import { isPermission } from "src/projects/app/permission";
import { MainContent } from "src/business/components/style-components/main-content";
import { request_func } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
const { TreeNode } = Tree;
const { Option } = Select;
// const FormItem = Form.Item;
/** 状态：新增角色视图 */
export interface AddRoleViewState extends ReactViewState {
    treeNode?: any;
    checkedKeys?: any;
    organization_list?: any;
    role_type_list?: any;
    /** 角色 */
    role?: any;
}

/** 组件：新增角色视图 */
export class AddRoleView extends ReactView<AddRoleViewControl, AddRoleViewState> {
    constructor(props: AddRoleViewControl) {
        super(props);
        this.state = {
            treeNode: [],
            checkedKeys: [],
            organization_list: [],
            role_type_list: [],
            role: {},
        };
    }
    componentDidMount() {
        /** 权限列表 */
        request_func(this, AppServiceUtility.role_service.get_permiss_list, [{}], (data: any) => {
            if (data.result.length) {
                let function_list: any = [];
                let res: any = [];
                data.result.map((val: any) => {
                    if (function_list.indexOf(val.function) > -1) {
                        res.map((item: any, i: number) => {
                            if (item.title === val.function) {
                                res[i].values.push({ id: val.id, value: val.permission });
                            }
                        });
                    } else {
                        let values = [];
                        let item = { id: val.id, value: val.permission };
                        function_list.push(val.function);
                        values.push(item);
                        res.push({ title: val.function, values });
                    }
                });

                let treeNode = res.map((val: any) => {
                    let tree = val.values.map((item: any) => {
                        return <TreeNode title={item.value} key={item.id} />;
                    });
                    return <TreeNode title={val.title} key={val.title}>{tree}</TreeNode>;
                });
                this.setState({ treeNode });
            } else {
                message.info('暂无权限');
            }
        });
        /** 组织机构列表 */
        request_func(this, AppServiceUtility.person_org_manage_service.get_organization_tree_list, [{}], (data: any) => {
            this.setState({
                organization_list: data.result
            });
        });
        /** 角色类型 */
        request_func(this, AppServiceUtility.role_service.get_role_type, [], (data: any) => {
            this.setState({
                role_type_list: data
            });
        });
        if (this.props.match!.params.key) {
            request_func(this, AppServiceUtility.role_service.get_role_single, [{ id: this.props.match!.params.key }], (data: any) => {
                if (data.length) {
                    this.setState({ role: data[0].role });
                }
                let checkedKeys: any = [];
                data.map((val: any) => {
                    checkedKeys.push(val.org_permiss_list[0].id);
                });
                this.setState({ checkedKeys });
            });
        }

    }
    /**
     * 权限选择
     * @param values 返回值
     */
    goBack = () => {
        this.props.history!.push(ROUTE_PATH.role);
    }
    onSelect = (selectedKeys: any, info: any) => {
        console.log('selected', selectedKeys, info);
    }

    onCheck = (checkedKeys: any, info: any) => {
        this.setState({ checkedKeys });
        console.log('onCheck', checkedKeys, info);
    }
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: any) => {
            console.info(this.state.checkedKeys);
            if (!this.state.checkedKeys.length) {
                message.info('请选择权限范围');
                return;
            }
            const obj = this.props.match!.params.key ? { id: this.props.match!.params.key } : {};
            let param = {
                name: values.name, ids: this.state.checkedKeys, organization_id: values.organization_id,
                role_type: values.role_type, comment: values.comment
            };
            param = Object.assign(param, obj);
            request_func(this, AppServiceUtility.role_service.update_role, [param], (data: any) => {
                message.info(data);
                this.goBack();
            });
        });
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        return (
            <MainContent>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <MainCard title='角色设置'>
                        <Row type="flex" justify="center">
                            <Col span={24}>
                                <Form.Item label='角色名称：'>
                                    {getFieldDecorator('name', {
                                        initialValue: this.state.role ? this.state.role.name : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入角色名称'
                                        }],
                                    })(
                                        <Input />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={24}>

                                <Form.Item label='所属组织：'>
                                    {getFieldDecorator('organization_id', {
                                        initialValue: this.state.role ? this.state.role.organization_id : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择所属组织',
                                        }],
                                    })(
                                        <TreeSelect
                                            showSearch={true}
                                            treeNodeFilterProp={'title'}
                                            allowClear={true}
                                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                            treeDefaultExpandAll={true}
                                            treeData={this.state.organization_list}
                                            placeholder={"请选择组织机构"}
                                        />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label='角色类型：'>
                                    {getFieldDecorator('role_type', {
                                        initialValue: this.state.role ? this.state.role.role_type : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择角色类型',
                                        }],
                                    })(
                                        <Select
                                            showSearch={true}
                                        >
                                            {this.state.role_type_list ? this.state.role_type_list.map((value: any, index: any) => {
                                                return (
                                                    <Option key={index} value={value}>{value}</Option>
                                                );
                                            }) : ''}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label='权限范围：'>
                                    {getFieldDecorator('permiss_list', {
                                        initialValue: '',
                                        rules: [{
                                            message: '请输入选择权限范围'
                                        }],
                                    })(
                                        <Tree
                                            checkable={true}
                                            onCheck={this.onCheck}
                                            checkedKeys={this.state.checkedKeys}
                                        // selectedKeys={['8b7d9b80-e356-11e9-98ab-a0a4c57e9ebe']}
                                        >
                                            {this.state.treeNode}
                                        </Tree>

                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label='说明：'>
                                    {getFieldDecorator('comment', {
                                        initialValue: this.state.role ? this.state.role.comment : '',
                                        rules: [{
                                            message: '请输入说明'
                                        }],
                                    })(
                                        <Input />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </MainCard>
                    <MainCard>
                        <Row type="flex" justify="center" className="ctrl-btns">
                            <Button type='ghost' name='返回' htmlType='button' onClick={this.goBack}>返回</Button>
                            <Button htmlType='submit' type='primary'>保存</Button>
                        </Row>
                    </MainCard>
                </Form>
            </MainContent >
        );
    }
}

/**
 * 控件：新增角色视图控制器
 * @description 新增角色视图
 */
@addon('AddRoleView', '新增角色视图', '新增角色视图')
@reactControl(Form.create<any>()(AddRoleView), true)
export class AddRoleViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
}